/*
 * Powered By Suemi Yi in 2015
 */
$.fn.extend({
	validate:function(settings,handler){
		if(!settings) settings={};
		if(!handler) handler=function(dom,msg){
			alert(msg.replace("*",""));
		};
		
		var operate=function(type,dom){
			success=false;
			var msg="";
			var name=$(dom).attr("name");
			var conf=settings[name];
			if(!conf) conf={};
			if(conf.type) msg=conf.type;
			else{
				var tmp=$(dom).attr("desc")
				if(tmp){
					msg+=$.trim(tmp);
				}
				else{
					tmp=$("[for="+name+"]");
					if(tmp.length>0) msg+=$.trim(tmp.text());
					else msg+=$.trim($(dom).attr("placeholder")?$(dom).attr("placeholder"):"");
				}
				
				switch(type){
					case "required":
						msg+="必须填写";
						break;
					case "maxlength":
						msg+="长度不得大于"+$(dom).attr("maxlength");
						break;
					case "email":
						msg+="不合规范";
						break;
					case "phone":
						msg+="不合规范";
						break;
					case "regx":
						msg+="不合规范";
						break;
					case "integer":
						msg+="大小必须在"+$(dom).attr("integer")+"范围内";
						break;						
					}
			}
			
			handler(dom,msg);
		};
		var success=true;
		
		
		$("[required]",this).each(function(index,element){
			if($(element).val()=="") {
				operate("required",element);
				return false;
			}
		});
		
		if(!success) return false;
		$("[integer]",this).each(function(index,element){
			var tmp=$(element);
			var scope=JSON.parse(tmp.attr("integer"));
			var num=parseInt(tmp.val());
			if (!(num==0 || num>0 ||num<=0)) {
				operate("integer",element);
				return false;			
			};
			if((num<scope[0])||(num>scope[1])){
				operate("integer",element);
				return false;
		    };
		});

		if(!success) return false;
		$("[maxlength]",this).each(function(index,element){
			var tmp=$(element);
			if(tmp.val().length>parseInt(tmp.attr("maxlength"))){
				operate("maxlength",element);
				return false;
			}
		});
		
		if(!success) return false;
		$("[name=email]",this).each(function(index,element){
			var tmp=$(element).val();
			if(!(/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/).test(tmp)){
				operate("email",element);
				return false;
		    };
		});
		
		if(!success) return false;
		$("[name=phone]",this).each(function(index,element){
			var tmp=$(element).val();
			if(!(/^1\d{10}$/).test(tmp)){
				operate("phone",element);
				return false;
		    };
		});
		
		if(!success) return false;
		$("[regx]",this).each(function(index,element){
			var tmp=$(element).val();
			var pattern=RegExp($(element).attr("regx"));
			if(!pattern.test(tmp)){
				operate("regx",element);
				return false;
			}
		});
		return success;
	}

});